package com.seqb.manage.file.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.ResultVo;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.exception.BdException;
import com.seqb.manage.file.dao.FileDao;
import com.seqb.manage.file.domain.FileDO;
import com.seqb.manage.file.service.FileService;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lilinshen
 * @title 请填写标题
 * @description 请填写相关描述
 * @date 2019/11/14
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileDao fileDao;

    @Override
    public FileDO get(Long id) {
        return fileDao.selectById(id);
    }

    @Override
    public Page<FileDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, FileDO.class);
        if (null != map.get("sort")) {
            queryWrapper.orderByAsc("id");
        } else {
            queryWrapper.orderByDesc("id");
        }
        return (Page<FileDO>) fileDao.selectList(queryWrapper);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, FileDO.class);
        return fileDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional
    public int save(FileDO file) {
        return fileDao.insert(file);
    }

    @Override
    @Transactional
    public int update(FileDO file) {
        return fileDao.updateById(file);
    }

    @Override
    @Transactional
    public int remove(Long id) {
        return fileDao.deleteById(id);
    }

    @Override
    @Transactional
    public int batchRemove(Long[] ids) {
        return fileDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional
    public ResultVo updateIds(String ids, Long domainId, String domainName, String domainField) {
        try {
            //先更新附件表的数据
            if (!StringUtils.isEmpty(ids)) {
                String[] idsArr = ids.split(",");
                for (String fileId : idsArr) {
                    FileDO file = new FileDO();
                    file.setId(Long.valueOf(fileId));
                    file.setDomainId(domainId);
                    file.setDomainName(domainName);
                    file.setDomainField(domainField);
                    int update = fileDao.updateById(file);
                    if (update <= 0) {
                        throw new BdException("操作失败！");
                    }
                }
            }
            //查询出对应附件表的数据
            Map<String, Object> params = new HashMap<>(16);
            params.put("domainId", domainId);
            params.put("domainName", domainName);
            params.put("domainField", domainField);
            params.put("sort", "id");
            List<FileDO> fileList = list(params);
            if (null != fileList && fileList.size() > 0) {
                //将fileUrl和id用字符串，进行拼接
                String fileUrl = fileList.stream().map(FileDO::getFileUrl).collect(Collectors.joining(","));
                String id = fileList.stream().map(file -> String.valueOf(file.getId())).collect(Collectors.joining(","));
                return ResultVo.ok().put("fileUrl", fileUrl).put("id", id);
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return ResultVo.error();
    }

    @Override
    public List<FileDO> listByIds(String fileIdsStr) {
        if (StringUtils.isEmpty(fileIdsStr)) {
            return null;
        }
        String[] fileIdsArr = fileIdsStr.split(",");
        Long[] fileIds = (Long[]) ConvertUtils.convert(fileIdsArr, Long.class);
        return fileDao.selectBatchIds(Arrays.asList(fileIds));
    }

}
